import cfg from "../../config";
import {getView} from "../../util/api";
import {Slider, sliderHide, sliderShow} from "../../lib/kslider";
import {Verify, formatBirthyDay} from "../../lib/kverify";
import {isArrContain, backPage, hideIdcard, formatDate, getPassengers} from "../../util/aid";
import {trips, perKey} from "../../util/const.config";
import Dialog from "../../lib/kdialog";

// import {jsonPass} from "../res/jsonPass"; //测试数据

const dialog = new Dialog();

const $ = require('../../lib/kdom');
let _view = require('raw-loader!./passenger.html');

let _data = null;//父页面的数据
let _opts = null;//父页面的参数
let _prnPidArr = null;// 选中的乘客id
let _currSaet = null;//父页面的参数
let _prnPassArr = null;// 选中的乘客
let _prnUrl = null;// 父页面的 url
let passDataArr = null;//乘客数据

export default class {
    path = '/train/passenger$';
    hash = '/train/passenger';
    title = '乘客';

    constructor(opt) {
        opt = opt || {};
        this.path = opt.path || this.path;
        this.hash = opt.hash || this.hash;
        this.title = opt.title || this.title;
    }

    // 输出视图
    view(cb) {
        if (!_view) {
            // 静态资源浏览器有缓存,增加时标,强制刷新!
            getView(`${cfg.train.view.passenger}?t=${(+new Date())}`, '', (rs) => {
                _view = rs;
                cb(null, _view);
            });
        } else
            cb(null, _view);
    }

    // 在已经加载的视图上操作
    bind(dv, params) {
        console.log('我是乘客:', params);

        _data = params.data;
        _opts = params.opts;
        // _opts = params.opts || {"date": "2017-07-16", "from": "CQW,重庆", "highMotor": false, "to": "BJP,北京", "url": "/train/home"};
        _prnUrl = params.url || '';
        _prnPassArr = params.passArr || '';
        _prnPidArr = params.pidArr || '';
        _currSaet = params.currSaet || '';

        // 初始化
        dialog.loading();

        // 获取乘客
        getPassengers((passengerData) => {
            loadPassengerFun(passengerData, _prnPidArr);
        });

        // 测试数据
        // loadPassengerFun(jsonPass, _prnPidArr);

        // backPage
        backPage('#pg-train-passenger', 'backPage', () => {
            if (_prnUrl) {
                $.router.go(_prnUrl, bookPassdata(), true);
            } else {
                $.router.back();
            }
        });

        // book
        if (_data && _opts) {
            addBookPassenger.style.display = 'table-cell';
        } else {
            addBookPassenger.style.display = 'none';
        }

        addBookPassenger.onclick = function () {
            $.router.go(_prnUrl, bookPassdata(), true);
        };
    }

    /*bind*/
}

function bookPassdata() {
    return {data: _data, opts: _opts, passArr: getSelectPassFun($.qus('#passengerList input[name="checkbox"]:checked')), currSaet: _currSaet}
}

// 添加
window.optPassenger = (id, idx) => {
    if (id && idx) {
        caretPassenger(passDataArr[idx], '修改乘机人');
    } else
        caretPassenger();
};

// 删除
window.delPassenger = (id) => {
    let nd = $.id(`passenger_${id}`);
    //  删除
    let delPassData = {
        id: id
    };
    ASYNC_POST(AJAX_PRO_URL, delPassData, function (err, rs) {
        if (rs) {
            let r = eval('(' + rs + ')');
            r = r.value;
            r = eval("(" + r + ")");
            console.log('删除乘客：', r);
            if (r && r.rc) {
                dialog.alert({content: '删除乘客成功！'});
                if (nd) {
                    nd.parentNode.removeChild(nd)
                }
            } else {
                dialog.alert({content: '删除乘客失败！'});
            }
        } else {
            dialog.alert({content: '删除乘客失败！'});
        }
    }, PUBLIC_PARAM.delPass);
};

function bindVerifyFun() {
    let rs = null;
    passName.onkeyup = () => {
        rs = verifyNamefun();
        // console.log(rs);
    };

    passCardNo.onkeyup = () => {
        rs = verifyCardNofun();
        // console.log(rs);
        setBirthdayFun(passCardNo, passAgeType, passBirthday, rs);
    };

    passMobile.onkeyup = () => {
        rs = verifyMobilefun();
        // console.log(rs);
    };
}

function setBirthdayFun(cardNoTag, ageTypeTag, birthdayTag, obj) {
    if (!cardNoTag && !ageTypeTAg && !birthdayTag && !obj) return;
    if (!obj.status) return;
    if (ageTypeTag.value == 1) {
        birthdayTag.value = formatBirthyDay(cardNoTag.value);
    }
}

function verifyNamefun() {
    return Verify.name(passName, '', true);
}
function verifyMobilefun() {
    return Verify.mobile(passMobile, '', true);
}
function verifyCardNofun() {
    let rs = null;
    if (passCardType.value == 1) {
        rs = Verify.IDcard(passCardNo, '', true);
    } else if (passCardType.value == 2) {
        rs = Verify.passport(passCardNo, '', true);
    }
    return rs;
}

function isAgeFun() {
    let rs = null;
    rs = Verify.isAgeFun(passBirthday.value, ( _opts ? _opts.date : new Date()), true, passBirthday, passAgeType);
    return rs;
}

// 获取选中的乘客
function getSelectPassFun(els) {
    if (!els) return; else if (els.length <= 0) return;
    let rc = [];
    for (let i = 0, len = els.length; i < len; i++) {
        rc.push(passDataArr[els[i].value]);
    }
    return rc;
}

//乘机人加载到页面
function loadPassengerFun(passengerArr, prnPidArr) {
    if (!passengerArr && passengerArr.Passenger) return;
    // console.log(passengerArr.Passenger);
    let rc = '';
    let tempStr = '';
    let reg = /[\u4e00-\u9fa5]/;
    let _name = null;
    let codeArr = null;
    let isChecked = '';
    passDataArr = passengerArr.Passenger; //全局缓存
    // passDataArr = passDataArr.sort((x, y) => {
    //     return x > y ? -1 : 1
    // });
    for (let i = 0, k1 = '', k2 = '', o = passDataArr, len = o.length; i < len; i++) {
        _name = o[i][perKey.Name];
        /*if (reg.test(_name)) {
         codeArr = convertPinyin(_name, pinyin);
         } else {
         codeArr = _name;
         }
         k2 = codeArr[0].substring(0, 1).toUpperCase();
         if (k1 !== k2) {
         rc += `<li class="list-group-title">${k2}</li>`;
         k1 = k2;
         }*/

        if (isArrContain(prnPidArr, o[i][perKey.id])) {
            isChecked = 'checked';
        } else {
            isChecked = '';
        }
        rc += `<li class="flex-block" id="passenger_${o[i][perKey.id]}">
                <label class="label-checkbox item-content" style="width: 72%;">
                    <input type="checkbox" name="checkbox" ${isChecked} value="${i}">
                    <div class="item-media"><i class="icon icon-form-checkbox"></i></div>
                    <div class="item-inner">
                        <div class="item-title-row">
                            <div class="item-title">
                                ${_name}<span class="text-disabled f075">（${o[i][perKey.AgeType]}）</span>
                            </div>
                        </div>
                        <div class="item-subtitle">${o[i][perKey.IDType]}： ${hideIdcard(o[i][perKey.IDNo]).hide}</div>
                    </div>
                </label>
               <div class="opt_button text-right">
                   <div class="text-danger" onclick="optPassenger('${o[i][perKey.id]}','${i}')"><span class="icon icon-edit"></span>修改</div>
                   <div class="text-disabled mt05" onclick="delPassenger('${o[i][perKey.id]}')"><span class="icon icon-remove"></span>删除</div>
               </div>
            </li>`;
    }
    $.html(passengerList, rc);
    dialog.close();
}

// 操作乘客
function caretPassenger(data, tlt) {
    console.log(data);
    data = data || [];
    let rc = `<header class="bar bar-nav thame-danger">
                    <span class="icon icon-left pull-left" id="hideCaretPass"></span>
                    <h1 class="title">${tlt ? tlt : '新增乘机人'}</h1>
                </header>
                <div class="content">
                  <div class="list-block mt0">
                    <ul>
                      <li>
                        <div class="item-content">
                          <div class="item-inner">
                            <div class="item-title label">乘客类型</div>
                            <div class="item-input">
                              <select id="passAgeType">
                                <option value="1" ${data[perKey.AgeType] == '成人' ? 'selected=true' : ''}>成人</option>
                                <option value="2" ${data[perKey.AgeType] == '儿童' ? 'selected=true' : ''}>儿童</option>
                              </select>
                            </div>
                          </div>
                        </div>
                      </li>
                      <li>
                        <div class="item-content">
                          <div class="item-inner">
                            <div class="item-title label">乘客姓名</div>
                            <div class="item-input">
                              <input id="passName" type="text" placeholder="输入乘客姓名" value="${data[perKey.Name] ? data[perKey.Name] : ''}">
                            </div>
                          </div>
                        </div>
                      </li>
                      <li>
                        <div class="item-content">
                          <div class="item-inner">
                            <div class="item-title label">证件类型</div>
                            <div class="item-input">
                              <select id="passCardType">
                                <option value="1" ${data[perKey.AgeType] == '身份证' ? 'selected=true' : ''}>身份证</option>
                                <option value="2" ${data[perKey.AgeType] == '护照' ? 'selected=true' : ''}>护照</option>
                                <!--<option value="5">港澳通行证</option>-->
                                <!--<option value="7">台湾居民来往大陆通行证</option>-->
                              </select>
                            </div>
                          </div>
                        </div>
                      </li>
                      <li>
                        <div class="item-content">
                          <div class="item-inner">
                            <div class="item-title label selfw">证件号码</div>
                            <div class="item-input">
                              <input type="text" placeholder="输入证件号码" id="passCardNo" value="${data[perKey.IDNo] ? data[perKey.IDNo] : ''}">
                            </div>
                          </div>
                        </div>
                      </li>
                      <li>
                        <div class="item-content">
                          <div class="item-inner">
                            <div class="item-title label">手机号码</div>
                            <div class="item-input">
                              <input type="tel" id="passMobile" placeholder="输入手机号" value="${data[perKey.Mobile] ? data[perKey.Mobile] : ''}">
                            </div>
                          </div>
                        </div>
                      </li> 
                      <li>
                        <div class="item-content">
                          <div class="item-inner">
                            <div class="item-title label">出生日期</div>
                            <div class="item-input">
                              <input type="date" value="${data[perKey.Birthday] ? formatDate('yyyy-MM-dd', data[perKey.Birthday]) : '2011-01-04'}" id="passBirthday">
                            </div>
                          </div>
                        </div>
                      </li>
                      <li>
                         <div class="button-item pt pb pl05 pr075">
                            <a class="button button-fill button-warning" id="savePassBtn">确认保存</a>
                        </div>
                      </li>
                    </ul>
                  </div>
                </div>`;
    new Slider({
        content: rc,
    });

    sliderShow();
    // 绑定验证
    bindVerifyFun();
    saveCaretPassFun(data);
    hideCaretPass.onclick = () => {
        sliderHide();
    };
}

function saveCaretPassFun(data) {
    savePassBtn.onclick = () => {
        let rs = null;
        rs = verifyNamefun();
        if (!rs.status) return false;
        rs = verifyCardNofun();
        if (!rs.status) return false;
        rs = isAgeFun();
        if (!rs.status) return false;
        //  保存
        let ageTypeVal = passAgeType.value;
        let _ageType = null;
        let _cardType = passCardType.value;
        let _idType = null;
        if (ageTypeVal === '1') {
            _ageType = '成人';
        } else {
            _ageType = '儿童'
        }
        if (_cardType === '1') {
            _idType = '身份证';
        } else if (_cardType === '2') {
            _idType = '护照';
        } else if (_cardType === '5') {
            _idType = '港澳通行证';
        } else if (_cardType === '7') {
            _idType = '台湾居民来往大陆通行证';
        }
        let savePassData = {
            "ID": data.length > 0 ? data[perKey.id] : "0",
            "AgeType": _ageType,
            "Name": passName.value,
            "IDType": _idType,
            "IDNo": passCardNo.value,
            "Phone": passMobile.value,
            "Birthday": passBirthday.value
        };
        console.log('savePassData', savePassData);
        let ICBC_AES = new ICBCAes();
        savePassData = JSON.stringify(savePassData);
        ICBC_AES.GetAesStr(savePassData, function (data, key) {
            console.log('加密乘客数据:', data);
            console.log('加密乘客数据KEY:', key);
            let formData = {
                json: data,
                encryptionAESPwd: key
            };
            console.log('加密数据formData', formData);
            ASYNC_POST(AJAX_PRO_URL, formData, function (err, rs) {
                if (rs) {
                    let r = eval('(' + rs + ')');
                    r = r.value;
                    r = eval("(" + r + ")");
                    console.log('保存乘客：', r);
                    if (r && r.ret == '1') {
                        dialog.alert({content: '保存乘客成功！'}, () => {
                            sliderHide();
                            // 获取乘客
                            dialog.loading();
                            getPassengers((passengerData) => {
                                loadPassengerFun(passengerData, _prnPidArr);
                            });
                        });
                    } else {
                        dialog.alert({content: '保存乘客失败！'});
                    }
                } else {
                    dialog.alert({content: '保存乘客失败！'});
                }
            }, PUBLIC_PARAM.savePass);
        });
    }


}

// 乘机人人类型切换绑定事件
function bindSelectPersonType() {
    birthLi.style.display = 'none';
    addSelectPassengerType.onchange = () => {
        if (addSelectPassengerType.value == '成人票') {
            birthLi.style.display = 'none';
        } else {
            birthLi.style.display = 'block';
        }
    };
}

/*function convertPinyin(arr, pinyin) {
 //汉字转换为拼音
 let obj = {
 A: [],
 B: [],
 C: [],
 D: [],
 E: [],
 F: [],
 G: [],
 H: [],
 I: [],
 J: [],
 K: [],
 L: [],
 M: [],
 N: [],
 O: [],
 P: [],
 Q: [],
 R: [],
 S: [],
 T: [],
 U: [],
 V: [],
 W: [],
 X: [],
 Y: [],
 Z: [],
 };
 //姓名分为英文和中文两种
 const chineseReg = /^[\u4e00-\u9fa5]+$/;
 const englishReg = /^[A-Za-z\/]+$/;
 for (let i = 0, len = arr.length; i < len; i++) {
 if (englishReg.test(arr[i][1])) {
 obj[arr[i][1].substr(0, 1).toUpperCase()].push(arr[i]);
 }
 if (chineseReg.test(arr[i][1])) {
 for (let key in pinyin) {
 if (pinyin[key].indexOf(arr[i][1].substr(0, 1)) != -1) {
 obj[key.substr(0, 1).toUpperCase()].push(arr[i]);
 }
 }
 }
 }
 // console.log(rc);
 for (let key in obj) {
 if (obj[key].length == 0) {
 delete obj[key];
 }
 }
 return obj;
 }*/

